package com.chen.controller;

import com.chen.bean.Result;
import com.chen.bean.User;
import com.chen.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

@RequestMapping("/user")
@CrossOrigin
@RestController
public class UserController {

    @Resource
    UserService userService;

    @PostMapping("/register")
    public Result register(@RequestBody User user){
        try {
            if (userService.getUser(user.getUsername())!=null){
                return Result.error(2,"用户名已存在",null);
            }
            userService.addUser(user);
            return Result.success(null);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(2,"出错了，请稍后尝试",null);
        }
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        try {
            User user1 = userService.getUser(user.getUsername());
            if (user1==null){
                return Result.error(2,"用户名不存在",null);
            }
            if (!user.getPassword().equals(user1.getPassword())){
                return Result.error(2,"密码错误",null);
            }
            user1.setPassword(null);
            if (user1.getPicture()==null|| Objects.equals(user1.getPicture(), ""))
                user1.setPicture("/static/user.png");
            return Result.success(user1);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(2,"出错了，请稍后重试",null);
        }
    }

    @PostMapping("/update")
    public Result updatePassword(@RequestBody User user){
        try {
            userService.updatePassword(user);
            return Result.success(null);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(2,"出错了，请稍后重试",null);
        }
    }

    @GetMapping("/getName")
    public Result getNameByTitle(String title){
        try {
            User user = userService.getUserByTitle(title);
            if (user.getPicture()==null|| Objects.equals(user.getPicture(), ""))
                user.setPicture("/static/user.png");
            return Result.success(user);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(2,"出错了，请稍后重试",null);
        }
    }

    @GetMapping("/loadUser")
    public Result loadUserAndAvatar(String username){
        try {
            User user = userService.getUser(username);
            return Result.success(user);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(2,"出错了，请稍后重试",null);
        }
    }
}
